/*
 *
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: CookieUtils.java
 *   @Date: 11/29/18 3:21 PM
 *   @Author: chenjun
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 *
 */

package io.bhex.baselib.network.Utils;

import android.content.Context;
import android.os.Build;
import android.text.TextUtils;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.ValueCallback;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import io.bhex.baselib.core.CApplication;
import io.bhex.baselib.network.Encode;
import io.bhex.baselib.network.HttpUtils;
import io.bhex.baselib.network.cookie.persistentcookiejar.ClearableCookieJar;
import io.bhex.baselib.network.cookie.persistentcookiejar.persistence.SharedPrefsCookiePersistor;
import io.bhex.baselib.utils.DebugLog;
import io.bhex.baselib.utils.DevicesUtil;
import io.bhex.baselib.utils.StringUtils;
import io.bhex.sdk.account.UserInfo;
import io.bhex.sdk.config.bean.BackupDomainBean;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.OkHttpClient;

public class CookieUtils {

	private void refreshCookie(){
		SharedPrefsCookiePersistor cookiePersistor =  new SharedPrefsCookiePersistor(CApplication.getInstance());
		if(cookiePersistor != null){
			cookiePersistor.loadAll();
		}
	}

	/**
	 * webview cookie同步
	 * @param context
	 * @param cookies
	 */
	public static void setCookies(Context context, List<Cookie> cookies) {
		if (UserInfo.isLogin()) {
			Map<String, String> deviceParams = DevicesUtil.getDeviceParams();
			String extDomain = "";
			for (Cookie cookie : cookies) {

				CookieSyncManager.createInstance(context);
				CookieManager cookieManager = CookieManager.getInstance();
				cookieManager.setAcceptCookie(true);
				// cookieManager.removeSessionCookie();// 移除
				String domain = cookie.domain();
				if(!TextUtils.isEmpty(domain)) {
					if(!domain.startsWith("."))
						domain = "." + domain;
					extDomain = domain;
					cookieManager.setCookie(domain, cookie.name() + "=" + cookie.value() + ";");// cookies是在HttpClient中获得的cookie
					DebugLog.e("COOKIE-1",domain + " " + cookie.name() + "=" + cookie.value() + ";");

					//TODO-0205 添加公共参数至cookie
					Iterator<String> keyIterator = deviceParams.keySet().iterator();
					while (keyIterator.hasNext()) {
						String key = keyIterator.next();
						cookieManager.setCookie(extDomain, key+ "=" + Encode.urlEncode(StringUtils.replaceSpace(deviceParams.get(key)))+";");
					}
//					cookieManager.setCookie(extDomain, Fields.PARAM_APP + "=" + DevicesUtil.getAppName(context)+ ";");// cookies是在HttpClient中获得的cookie
//					cookieManager.setCookie(extDomain, Fields.PARAM_APPID + "=" + DevicesUtil.getPackageName(context)+ ";");// cookies是在HttpClient中获得的cookie
//					cookieManager.setCookie(extDomain, Fields.PARAM_VERSION + "=" + DevicesUtil.getAppVersionName(context)+ ";");// cookies是在HttpClient中获得的cookie
//					cookieManager.setCookie(extDomain, Fields.PARAM_CHANNEL + "=" + DevicesUtil.getChannel(context)+ ";");// cookies是在HttpClient中获得的cookie
//					cookieManager.setCookie(extDomain, Fields.DEVICE_PARAM_OS + "=" + "Android"+ ";");// cookies是在HttpClient中获得的cookie
//					cookieManager.setCookie(extDomain, Fields.PARAM_PLATFORM + "=" + DevicesUtil.getSdkVersion(context)+ ";");// cookies是在HttpClient中获得的cookie
//					//TODO-0205 增加参数IMEI
//					cookieManager.setCookie(extDomain, Fields.PARAM_IMEI + "=" + DevicesUtil.getDeviceID(context)+ ";");// cookies是在HttpClient中获得的cookie

					if (Build.VERSION.SDK_INT < 21) {//21 Build.VERSION_CODES.LOLLIPOP
						CookieSyncManager.getInstance().sync();
					} else {
						cookieManager.flush();
					}
				}
			}
		}

	}

	/**
	 * webview cookie同步
	 * @param context
	 * @param backupDomains
	 */
	public static void setDomainsCookies(Context context,List<BackupDomainBean> backupDomains) {
		if (UserInfo.isLogin()) {
//			DebugLog.e("COOKIE-2-start","---------------------------");
			SharedPrefsCookiePersistor cookiePersistor = new SharedPrefsCookiePersistor(CApplication.getInstance());
			List<Cookie> cookies = null;

			if (cookiePersistor != null) {
				cookies = cookiePersistor.loadAll();
			}
			if (cookies != null && !cookies.isEmpty()) {
				String extDomain = "";
				if (backupDomains != null && backupDomains.size() > 0) {

					final Map<String, String> deviceParams = DevicesUtil.getDeviceParams();

					CookieSyncManager.createInstance(context);
					CookieManager cookieManager = CookieManager.getInstance();
					cookieManager.setAcceptCookie(true);
					// cookieManager.removeSessionCookie();// 移除

					for (BackupDomainBean backupDomainBean : backupDomains) {
						String domain = backupDomainBean.getDomain();
						if (!TextUtils.isEmpty(domain)) {
							if (domain.contains(":")) {
								domain = domain.split(":")[0];
							}
							if (!domain.startsWith("."))
								domain = "." + domain;
							extDomain = domain;

							for (final Cookie cookie : cookies) {

								if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
									cookieManager.setCookie(domain, cookie.name() + "=" + cookie.value() + ";", new ValueCallback<Boolean>() {
										@Override
										public void onReceiveValue(Boolean value) {
//											DebugLog.e("COOKIE-2-callback", value + " " + cookie.name() + "=" + cookie.value() + ";");
										}
									});// cookies是在HttpClient中获得的cookie
								}
//								DebugLog.e("COOKIE-2",domain + " " + cookie.name() + "=" + cookie.value() + ";");

							}
							//TODO-0205 添加公共参数至cookie
							Iterator<String> keyIterator = deviceParams.keySet().iterator();
							while (keyIterator.hasNext()) {
								final String key = keyIterator.next();
								if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
									if (!TextUtils.isEmpty(deviceParams.get(key))){
										cookieManager.setCookie(extDomain, key+ "=" + Encode.urlEncode(StringUtils.replaceSpace(deviceParams.get(key)))+";");
									}
								}
							}

						}
					}

					if (Build.VERSION.SDK_INT < 21) {//21 Build.VERSION_CODES.LOLLIPOP
						CookieSyncManager.getInstance().sync();
					} else {
						cookieManager.flush();
					}

				}
			}
		}

	}

	public static void syncCookie(Context context) {
		CookieSyncManager.createInstance(context);
		CookieSyncManager.getInstance().sync();
	}

	public static void clearCookies(Context context) {
		// Edge case: an illegal state exception is thrown if an instance of
		// CookieSyncManager has not be created. CookieSyncManager is normally
		// created by a WebKit view, but this might happen if you start the
		// app, restore saved state, and click logout before running a UI
		// dialog in a WebView -- in which case the app crashes
		CookieSyncManager.createInstance(context);
		CookieManager cookieManager = CookieManager.getInstance();
		cookieManager.removeAllCookie();
		CookieSyncManager.getInstance().sync();

		SharedPrefsCookiePersistor cookiePersistor =  new SharedPrefsCookiePersistor(CApplication.getInstance());
		if (cookiePersistor != null) {
			cookiePersistor.clear();
		}
		OkHttpClient httpClient = HttpUtils.getInstance().getHttpClient();
		if (httpClient != null) {
			CookieJar cookieJar = httpClient.cookieJar();
			if (cookieJar != null) {
				ClearableCookieJar clearableCookieJar = (ClearableCookieJar) cookieJar;
				clearableCookieJar.clear();
			}
		}

	}

	public static String getCookieToken(){
		SharedPrefsCookiePersistor cookiePersistor =  new SharedPrefsCookiePersistor(CApplication.getInstance());
		List<Cookie> cookies = null;

		String tokenValue = "";
		if(cookiePersistor != null)
			cookies = cookiePersistor.loadAll();
		for (Cookie cookie : cookies) {

			if(cookie.name().contains("au_token")){
				tokenValue = cookie.value();
			}
		}
		return tokenValue;
	}

	public static String getCToken(){
		SharedPrefsCookiePersistor cookiePersistor =  new SharedPrefsCookiePersistor(CApplication.getInstance());
		List<Cookie> cookies = null;

		String tokenValue = "";
		if(cookiePersistor != null)
			cookies = cookiePersistor.loadAll();
		for (Cookie cookie : cookies) {

			if(cookie.name().contains("c_token")){
				tokenValue = cookie.value();
			}
		}
		return tokenValue;
	}
}
